/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.ce.webservice;

import com.bionic.ce.ws.Currency;
import com.bionic.ce.ws.CurrencyConvertor;
import com.bionic.ce.ws.CurrencyConvertorSoap;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 *
 * @author Jarik
 */
public class WebService {

    public WebService() {
        currencyList.add(Currency.USD);
        currencyList.add(Currency.EUR);
        currencyList.add(Currency.UAH);
        currencyList.add(Currency.RUB);
    }
    private List<CurrencyRate> rateList = new ArrayList<CurrencyRate>();
    private HashSet<Currency> currencyList = new HashSet<Currency>();

    public HashSet<Currency> getCurrencyList() {
        return currencyList;
    }

    public void setCurrencyList(HashSet<Currency> currencyList) {
        this.currencyList = currencyList;
    }

    public void addCurrency(Currency currency) {
        currencyList.add(currency);
    }

    //получения курса обмена с помощью метода getCurrencyConvertorSoap12 из веб-сервиса
    private double conversionRate(Currency fromCurrency, Currency toCurrency) throws MalformedURLException {
        CurrencyConvertor service = new CurrencyConvertor(new URL("http://www.webservicex.net/CurrencyConvertor.asmx?WSDL"));
        CurrencyConvertorSoap port = service.getCurrencyConvertorSoap12();
        return port.conversionRate(fromCurrency, toCurrency);
    }

    //создание списка курсов обмена указанных валют
    public List<CurrencyRate> createRateList() throws MalformedURLException, IOException {
        for (Currency cur_i : currencyList) {
            for (Currency cur_j : currencyList) {
                if (cur_i != (cur_j)) {
                    CurrencyRate curRate = new CurrencyRate();
                    curRate.setFromCurrency(cur_i);
                    curRate.setToCurrency(cur_j);
                    try {
                        curRate.setRate(conversionRate(cur_i, cur_j));
                    } catch (Exception e) {
                        throw new IOException("Web service is currently unavailable");
                    }
                        rateList.add(curRate);
                    }
                }
            }
            return rateList;
        }
    }
